#!/usr/bin/env sh

# draw a parchment around a text file
# usage:
#   $ parchment [-B DESIGN] [FILE]

PATH=$PATH:$(cd "$(dirname "$0")" && pwd -P)

if [ "$1" = "-B" ]
then
  box=$2
  shift 2
fi

# get file, or -
file=${1:--}
if [ "$file" != "-" ] && [ ! -e "$file" ]
then
  echo "error: parchment, file not found '$file'" >&2
  exit 1
fi

# width defaults to 80 characters
COLUMNS=${COLUMNS:-80}

if [ "$COLUMNS" -ge 80 ] || [ -n "$box" ]
then
  reflow_width=$((COLUMNS - 30))
else
  reflow_width=$((COLUMNS-5))  # -4 for the ASCII frame, -1 for the margin added by the pager
  box=ASCII
fi

# limit the reflow width to 100 to avoid very wide parchments
# [ "$reflow_width" -gt 100 ] && reflow_width=100

if [ -z "$box" ]
then
  n=$(RANDOM)
  case "$((n%9))" in
    0) box="Parchment1";;
    1) box="Parchment2";;
    2) box="Parchment3";;
    3) box="Parchment4";;
    4) box="Parchment5";;
    5) box="Parchment6";;
    6) box="Parchment7";;
    7) box="Parchment8";;
    8) box="Parchment9";;
  esac
fi

echo
box.sh -B "$box" -R "$reflow_width" "$file"
echo

